package com.topisv.tms.web.stock.instorage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.dto.InstorageInfoDto;
import com.topisv.tms.entity.stock.instorage.InstorageInfo;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.instorage.InstorageInfoService;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 入库信息
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/instorageInfo")
public class InstorageInfoController {

	private static final Logger logger = LoggerFactory.getLogger(InstorageInfoController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private InstorageInfoService instorageInfoService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	
	//导向入库单列表页面
	@RequestMapping(value = "v2_toInstorageInfoPage")
	public String toInstorageInfoPage(Model model, ServletRequest request) {
		try {
			//当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
			    //初始化仓库数据
				if(StringUtils.isNotBlank(customerCode)){
					List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
					model.addAttribute("warehouseList", warehouseList);
					model.addAttribute("_customerCode", customerCode);
				}
			}
			List<AreaGroup> warehouseList  = areaGroupService.findByAreaGroups(curUser.areagroups);
			model.addAttribute("warehouseList", warehouseList);
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "instorage/instorageInfo";
	}
		
	//查询入库信息
	@RequestMapping(value = "v2_queryInstorageInfo")
	public String queryInstorageInfo(Model model, ServletRequest request) {
		try {
			
			//当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String)param.get("warehouseCode");
			String billCode=(String)param.get("billCode");
			String sku=(String)param.get("sku");
			
			//时间筛选
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			
			//初始化仓库数据
			String customerCode=(String)param.get("customerCode");
			List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
			model.addAttribute("warehouseList", warehouseList); 
			
			//入库信息
			List<InstorageInfoDto> dtoList = this.instorageInfoService.loadInfoDtoByParam(param);
			model.addAttribute("dtoList", dtoList);
			
			model.addAttribute("_customerCode", customerCode);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_billCode", billCode);
			model.addAttribute("_sku", sku);
			model.addAttribute("_fromDate", fromDateStr);
			model.addAttribute("_toDate", toDateStr);
			
			
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "instorage/instorageInfo";
	}
	
    /**
     * 查询入库明细
     * @param model
     * @param request
     * @return
     */
	@RequestMapping(value = "v2_toDetailInfo")
	public String toDetailInfo(Model model, ServletRequest request) {
		try {
			
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String customerCode=(String)param.get("customerCode_hidden");
			String warehouseCode=(String)param.get("warehouseCode_hidden");
			String billCode=(String)param.get("billCode_hidden");
			String sku=(String)param.get("sku_hidden");
			
			//时间筛选
			String fromDateStr=(String) param.get("fromDate_hidden");
			String toDateStr=(String) param.get("toDate_hidden");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			
			//封装查询参数
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("billCode", billCode);
			param.put("sku", sku);
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			
			
			//入库信息
			List<InstorageInfo> infoList = this.instorageInfoService.loadByParam(param);
			model.addAttribute("infoList", infoList);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "stock/instorage/instorageInfoDetail";
	}
	/**
	 * 导出入库明细
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "exportExcel")
	public void outexportExcel(ServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
		String fromTm = (String)searchParams.get("fromDate");
		String toTm = (String)searchParams.get("toDate");
		Date fromDate=null;
		Date toDate=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(StringUtils.isNotEmpty(fromTm)){
			fromDate=sdf.parse(fromTm+" 00:00:00");
		}
		if(StringUtils.isNotEmpty(toTm)){
			toDate=sdf.parse(toTm+" 23:59:59");
		}
		String warehouseCode=(String)searchParams.get("warehouseCode");
		String customerCode=(String)searchParams.get("customerCode");
		String billCode=(String)searchParams.get("billCode");
		String sku=(String)searchParams.get("sku");
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("customerCode", customerCode);
		param.put("warehouseCode", warehouseCode);
		param.put("fromDate", fromDate);
		param.put("toDate", toDate);
		param.put("billCode", billCode);
		param.put("sku", sku);
		
		//查询网点
		AreaGroup area = areaGroupService.findByGroupCode(warehouseCode);
		//根据条件查询出入库信息
		List<InstorageInfo> infoList = instorageInfoService.loadByParam(param);
		logger.info("=======开始导出入库信息=======");
		
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition","attachment; filename=" + customerCode +fromTm + toTm+ ".xls");
		
		WritableWorkbook book  =  Workbook.createWorkbook(response.getOutputStream());
		WritableSheet sheet  =  book.createSheet( "Sheet1 ",0);
		//商家编码,仓库名称，入库单号 ，SKU，数量,时间，是否破损
		sheet.setColumnView(0, 20);
		sheet.setColumnView(1, 20);
		sheet.setColumnView(2, 25);
		sheet.setColumnView(3, 20);
		sheet.setColumnView(4, 20);
		sheet.setColumnView(5, 25);
		sheet.setColumnView(6, 20);
		
		Label label1 = new  Label(0,0 ,"商家编码");
		sheet.addCell(label1);
		Label label2 = new  Label(1,0 ,"仓库名称");
		sheet.addCell(label2);
		Label label3 = new  Label(2,0 ,"入库单号");
		sheet.addCell(label3);
		Label label4 = new  Label(3,0 ,"入库类型");
		sheet.addCell(label4);
		Label label5 = new  Label(4,0 ,"SKU");
		sheet.addCell(label5);
		Label label6 = new  Label(5,0 ,"商品名称");
		sheet.addCell(label6);
		Label label7 = new  Label(6,0 ,"数量");
		sheet.addCell(label7);
		Label label8 = new  Label(7,0 ,"时间");
		sheet.addCell(label8);
		Label label9 = new  Label(8,0 ,"是否破损");
		sheet.addCell(label9);
		int index_1 = 1;
		for(InstorageInfo info:infoList){
				Label label01 = new  Label(0,index_1,info.getCustomerCode());
				sheet.addCell(label01);
				Label label02 = new  Label(1,index_1,area.getGroupName());
				sheet.addCell(label02);
				Label label03 = new  Label(2,index_1,info.getBillCode());
				sheet.addCell(label03);
				// 入库类型
				String instorageType="";
				switch (info.getBillType()) {
				case "customer":
					instorageType="采购入库";
					break;
				case "allot":
					instorageType="调拨入库";
					break;
				case "returnOrder":
					instorageType="退回入库";
					break;
				case "preOrder":
					instorageType="预约入库";
					break;
				case "check":
					instorageType="盘点入库";
					break;
				}
				Label label04 = new  Label(3,index_1,instorageType);
				sheet.addCell(label04);
				
				Label label05 = new  Label(4,index_1,info.getSku());
				sheet.addCell(label05);
				//商品名称
				EdiGoodsSku ediGoodsSku = ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, info.getSku());
				Label label06 = new  Label(5,index_1,ediGoodsSku!=null ? ediGoodsSku.getSkuName():"");
				sheet.addCell(label06);
				
				Label label07 = new  Label(6,index_1,info.getNum().toString());
				sheet.addCell(label07);
				Label label08 = new  Label(7,index_1,info.getOpeTime().toString());
				sheet.addCell(label08);
				String errorFlag = "";
				if("error".equals(info.getErrorFlag())){
					errorFlag = "破损件";
				}else if("noterror".equals(info.getErrorFlag())){
					errorFlag = "完好件";
				}
				Label label09 = new  Label(8,index_1,errorFlag);
				sheet.addCell(label09);
				index_1++;
		}
		book.write();
        book.close();
	}
}
